<?php

	/**
	 * File : ssh_functions.php
	 * Description : Fonctions d'accès au protocol SSH
	 * Date : 07.08.2012 14:12:56
	 * 
	 * This file is part of Phenix.  Phenix is free software: you can
	 * redistribute it and/or modify it under the terms of the GNU General Public
	 * License as published by the Free Software Foundation, version 2.
	 *
	 * This program is distributed in the hope that it will be useful, but WITHOUT
	 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
	 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
	 * details.
	 *
	 * You should have received a copy of the GNU General Public License along with
	 * this program; if not, write to the Free Software Foundation, Inc., 51
	 * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
	 *
	 * Nils Schaetti <n.schaetti@gmail.com>
	**/

	/***************************************
	 * Fonctions de connexion au serveur SSH
	***************************************/

	// Erreur de connexion
	define('CONNECTION_ERROR','-1');
	define('AUTH_ERROR','-2');

	/*
	 * Connexion au serveur SSH
	*/
	function lp_ssh_connect($host,$user,$password,$port=22)
	{
		// Connexion
		if(!($cons=ssh2_connect($host,$port)))
			return(CONNECTION_ERROR);
		// Authentification
		if(!ssh2_auth_password($cons,$user,$password))
			return(AUTH_ERROR);
		return($cons);
	}

	/*
	 * Execute une commande et renvoie le résultat
	*/
	function lp_execute($con,$command)
	{
		// Execute une commande
		if(!($stream = ssh2_exec($con,$command)))
			return -1;
		else
		{
			// Récupère les données
			stream_set_blocking($stream,true);
			$data = "";
			while($buf = fread($stream,4096))
			{
				$data .= $buf;
			}
		}
		fclose($stream);
		return($data);
	}

	/*
	 * Ferme la connexion
	*/
	function lp_ssh_close($con)
	{
		lp_execute($con,'exit');
	}


?>

